import java.util.Random;
/**
 * 根据链表的长度(NODE_LIST)与遍历链表获得的链表长度(sizeLinkList)来判断是否有环,如果NODE_LIST < sizeLinkList则有环
 */
public class ChangzuzheCircle {
    public static final int NODE_LIST = 10;
    public static void main(String[] args) {
        Node head = null;
        Node pre = null;
        for (int i = 1;i <= NODE_LIST;i++) {
            Node node = new Node();
            node.data = i+"";
            if (i == 1) {
                head = node;
            }
            if (pre != null) {
                pre.next = node;
            }
            pre = node;
        }

       boolean hasCircle = hasCircle(head,NODE_LIST);
       System.out.println("has circle:" + hasCircle);
	   //创建环的入口
       int circleNum = new Random().nextInt(NODE_LIST);
       System.out.println("circleNum:" + circleNum);
       Node current = head;
       Node circleIn = null;
       while (true) {
           if ((circleNum+"").equals(current.data)) {
               circleIn = current;
           }
           if (current.next == null) {
               current.next = circleIn;
               break;
           }
           current = current.next;
       }
       hasCircle = hasCircle(head,NODE_LIST);
       System.out.println("has circle:" + hasCircle);
    }

    public static boolean hasCircle(Node head,int sizeLinkList) {
        int size = 1;
        Node current = head;
        while (current.next != null) {
            if (++size > sizeLinkList) {
                System.out.println("size:" + size + ";sizeLinkList:" + sizeLinkList);
                return true;
            }
            current = current.next;
        }
        return false;
    }

    public static void printNode(Node node) {
        if (node != null) {
            System.out.print(node.data);
            if (node.next != null ) {
                System.out.print("->");
                printNode(node.next);
            } else {
                System.out.print("\n");
            }
        }
    }
}

class Node {
    String data;
    Node next;
}
